<?php
/**
 * 全局通用函数
 * @author Flc <2015-08-13 09:44:56>
 */


//获取IP
function getip() {
    static $realip = NULL;
    if ($realip !== NULL) {
        return $realip;
    }
    if (isset($_SERVER)) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            /* 取X-Forwarded-For中第x个非unknown的有效IP字符? */
            foreach ($arr as $ip) {
                $ip = trim($ip);
                if ($ip != 'unknown') {
                    $realip = $ip;
                    break;
                }
            }
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        } else {
            if (isset($_SERVER['REMOTE_ADDR'])) {
                $realip = $_SERVER['REMOTE_ADDR'];
            } else {
                $realip = '127.0.0.1';
            }
        }
    } else {
        if (getenv('HTTP_X_FORWARDED_FOR')) {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('HTTP_CLIENT_IP')) {
            $realip = getenv('HTTP_CLIENT_IP');
        } else {
            $realip = getenv('REMOTE_ADDR');
        }
    }
    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '127.0.0.1';
    return $realip;
}


//返回时间格式  $time:时间戳
function mydate($time,$format='Y-m-d H:i:s'){
	return date($format,$time);
}

//完全过虑HTML结构
function clearHtml($str){
	$str = strip_tags($str);
	//首先去掉头尾空格
	$str = trim($str);
	//接着去掉两个空格以上的
	$str = preg_replace('/\s(?=\s)/', '', $str);
	//最后将非空格替换为一个空格
	$str = preg_replace('/[\n\r\t]/', ' ', $str);
	$str = str_replace('&nbsp;','',$str);
	return trim($str);
}

//检测是否为HTTPS
function IS_HTTPS(){
    if(!isset($_SERVER['HTTPS']))  return FALSE;
    if($_SERVER['HTTPS'] === 1){  //Apache
        return TRUE;
    }elseif($_SERVER['HTTPS'] === 'on'){ //IIS
        return TRUE;
    }elseif($_SERVER['SERVER_PORT'] == 443){ //其他
        return TRUE;
    }
    return FALSE;
}




/*
 +----------------------------------------------------------
 * 产生随机字串，可用来自动生成密码 默认长度6位 字母和数字混合
 +----------------------------------------------------------
 * @param string $len 长度
 * @param string $type 字串类型
 * 0 字母 1 数字 其它 混合
 * @param string $addChars 额外字符
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function rand_string($len=6,$type='1',$addChars='') {
    $str ='';
    switch($type) {
        case 0:
            $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.$addChars;
            break;
        case 1:
            $chars= str_repeat('0123456789',3);
            break;
        case 2:
            $chars='ABCDEFGHJKLMNPQRSTUVWXYZ'.$addChars;
            break;
        case 3:
            $chars='abcdefghijklmnopqrstuvwxyz'.$addChars;
            break;
        default :
            // 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数
            $chars='ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'.$addChars;
            break;
    }
    if($len>10 ) {//位数过长重复字符串一定次数
        $chars= $type==1? str_repeat($chars,$len) : str_repeat($chars,5);
    }
    $chars   =   str_shuffle($chars);
    $str     =   substr($chars,0,$len);
    return $str;
}


//数字格式化 $f ： 数据  ； $len 截取长度
function decmialStr($f, $len=2){
	return sprintf("%01.".$len."f", $f);
}


//货币转换，带货币符号及，分隔    $money 货币金额    $needPoint 是否保留小数点
function moneyStr($money, $needPoint=true, $symbol){
	if(!is_numeric($money)) return $symbol."0.00";
	$sb = "";
	if($money<0){
		$sb="-";
		$money = decmialStr($money*(-1));
	}

	$dot = explode(".",$money);
    $tmp_money = strrev_utf8($dot[0]);
    $format_money = "";
    for($i = 3;$i<strlen($dot[0]);$i+=3){
        $format_money .= substr($tmp_money,0,3).",";
         $tmp_money = substr($tmp_money,3);
     }
    $format_money .=$tmp_money;
    if(empty($sb)) $format_money = $symbol.strrev_utf8($format_money);
    else $format_money = $symbol."-".strrev_utf8($format_money);
    if($dot[1] && $needPoint) return $format_money.".".$dot[1];
	else return $format_money;
}

//返回保留2位小数，逗号隔开的金额（decmialStr及moneyStr组合）
function decMoneyStr($str){
	return moneyStr(decmialStr($str));
}

function strrev_utf8($str) {
    return join("", array_reverse(
        preg_split("//u", $str)
    ));
}


//计算两个时间戳的间隔 返回数组
function timediff($begin_time,$end_time,$type)
{   
    //只计算开始与结束的差距，可以值为负数
    if($type == 'cn'){
        $timediff = $end_time - $begin_time;
       
        $days = intval( $timediff / 86400 );
        $remain = $timediff % 86400;
        $hours = intval( $remain / 3600 );
        $remain = $remain % 3600;
        $mins = intval( $remain / 60 );
        $secs = $remain % 60;
        $res = array( "day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs );
        return $res;
    }
    if ( $begin_time < $end_time ) {
        $starttime = $begin_time;
        $endtime = $end_time;
    } else {
        $starttime = $end_time;
        $endtime = $begin_time;
    }
    $timediff = $endtime - $starttime;
    $days = intval( $timediff / 86400 );
    $remain = $timediff % 86400;
    $hours = intval( $remain / 3600 );
    $remain = $remain % 3600;
    $mins = intval( $remain / 60 );
    $secs = $remain % 60;
    $res = array( "day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs );
    return $res;
}

// 获取当前页面完整URL地址
function getUrl() {
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
    return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}

//获取当前页面URL头(含端口) （如，http://localhost:8888）
function getHttpUrl() {
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
	return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '');
}

//显示信息 $msg 为弹出信息； $gourl为跳转地址，默认为返回上一页
function showMsg($msg='', $gourl='-1'){
	if($gourl != '-1'){
		echo '<script>alert("'.$msg.'");location.href="'.$gourl.'";</script>';
		exit;
	}else{
		echo '<script>alert("'.$msg.'");history.go(-1);</script>';
		exit;
	}
}


/**
 * 安全过滤函数
 *
 * @param $string
 * @return string
 */
function safe_replace($string) {
	$string = str_replace('%20','',$string);
	$string = str_replace('%27','',$string);
	$string = str_replace('%2527','',$string);
	$string = str_replace('*','',$string);
	$string = str_replace('"','&quot;',$string);
	$string = str_replace("'",'',$string);
	$string = str_replace('"','',$string);
	$string = str_replace(';','',$string);
	$string = str_replace('<','&lt;',$string);
	$string = str_replace('>','&gt;',$string);
	$string = str_replace("{",'',$string);
	$string = str_replace('}','',$string);
	$string = str_replace('\\','',$string);
	return $string;
}

/**
 * xss过滤函数
 *
 * @param $string
 * @return string
 */
function remove_xss($string) {
    $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $string);

    $parm1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');

    $parm2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');

    $parm = array_merge($parm1, $parm2);

	for ($i = 0; $i < sizeof($parm); $i++) {
		$pattern = '/';
		for ($j = 0; $j < strlen($parm[$i]); $j++) {
			if ($j > 0) {
				$pattern .= '(';
				$pattern .= '(&#[x|X]0([9][a][b]);?)?';
				$pattern .= '|(&#0([9][10][13]);?)?';
				$pattern .= ')?';
			}
			$pattern .= $parm[$i][$j];
		}
		$pattern .= '/i';
		$string = preg_replace($pattern, ' ', $string);
	}
	return $string;
}

/**
 * 参数解释
 * $string： 明文 或 密文
 * $operation：DECODE表示解密,ENCODE表示加密;
 * $key： 密匙
 * $expiry：密文有效期
 * $length: 是否增加随机密钥，当此值为 0 时，则不产生随机密钥
 */
function AuthCode($string, $operation='ENCODE', $key='', $expiry=0, $length=4){
	// 动态密匙长度，相同的明文会生成不同密文就是依靠动态密匙
	// 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
	// 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
	// 当此值为 0 时，则不产生随机密钥
	$ckey_length = $length;
	// 密匙
	$key = md5($key ? $key : C('AUTH_KEY'));
	// 密匙a会参与加解密
	$keya = md5(substr($key, 0, 16));
	// 密匙b会用来做数据完整性验证
	$keyb = md5(substr($key, 16, 16));
	// 密匙c用于变化生成的密文
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
	// 参与运算的密匙
	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);
	// 明文，前10位用来保存时间戳，解密时验证数据有效性，10到26位用来保存$keyb(密匙b)，解密时会通过这个密匙验证数据完整性
	// 如果是解码的话，会从第$ckey_length位开始，因为密文前$ckey_length位保存 动态密匙，以保证解密正确
	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);
	$result = '';
	$box = range(0, 255);
	$rndkey = array();

	// 产生密匙簿
	for($i = 0; $i <= 255; $i++)
	{
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	// 用固定的算法，打乱密匙簿，增加随机性，好像很复杂，实际上并不会增加密文的强度
	for($j = $i = 0; $i < 256; $i++)
	{
		//$j是三个数相加与256取余
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	// 核心加解密部分
	for($a = $j = $i = 0; $i < $string_length; $i++)
	{
		//在上面基础上再加1 然后和256取余
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;//$j加$box[$a]的值 再和256取余
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		// 从密匙簿得出密匙进行异或，再转成字符，加密和解决时($box[($box[$a] + $box[$j]) % 256])的值是不变的。
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE')
	{
		// substr($result, 0, 10) == 0 验证数据有效性
		// substr($result, 0, 10) - time() > 0 验证数据有效性
		// substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16) 验证数据完整性
		// 验证数据有效性，请看未加密明文的格式
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16))
		{
			return substr($result, 26);
		}
		else
		{
			return '';
		}
	}
	else
	{
		// 把动态密匙保存在密文里，这也是为什么同样的明文，生产不同密文后能解密的原因
		// 因为加密后的密文可能是一些特殊字符，复制过程可能会丢失，所以用base64编码
		return $keyc.str_replace('=', '', base64_encode($result));
	}
}



//生成UUID
function uuid(){
    if (function_exists('com_create_guid')){
        $uuid = com_create_guid();
    }else{
        mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = chr(123)// "{"
                .substr($charid, 0, 8).$hyphen
                .substr($charid, 8, 4).$hyphen
                .substr($charid,12, 4).$hyphen
                .substr($charid,16, 4).$hyphen
                .substr($charid,20,13)
                .chr(125);// "}"
    }
	$uuid = trim($uuid, '{}');
	return $uuid;
}


/**
 * 通过IP获取对应城市信息(该功能基于淘宝第三方接口)
 * @param $ip IP地址,如果不填写，则为当前客户端IP
 * @return  如果成功，则返回数组信息，否则返回false
 */
function getipinfo($ip){
	if(empty($ip)) $ip=getIP();
	$url='http://ip.taobao.com/service/getIpInfo.php?ip='.$ip;
	$result = file_get_contents($url);
	$result = json_decode($result,true);
	if($result['code']!==0 || !is_array($result['data'])) return false;
	return $result['data'];
}

/**
 * combineURL
 * 拼接url
 * @param string $baseURL   基于的url
 * @param array  $keysArr   参数列表数组
 * @return string           返回拼接的url
 */
function combineURL($baseURL, $keysArr){
    if(empty($keysArr) || !is_array($keysArr)) return $baseURL;

    $combined = $baseURL."?";
    $valueArr = array();
    foreach($keysArr as $key => $val){
        $valueArr[] = "$key=".urlencode($val);
    }
    $keyStr = implode("&",$valueArr);
    $combined .= ($keyStr);
    return $combined;
}

/**
 * 服务器通过get请求获得内容
 * @param  string $baseURL 基础URL
 * @param  array $keysArr 请求参数
 * @return string          [description]
 */
function http_gets($baseURL, $keysArr){
    $url = combineURL($baseURL, $keysArr);

    $ch = curl_init();
    if(stripos($url,"https://")!==FALSE){
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    $sContent = curl_exec($ch);
    $aStatus = curl_getinfo($ch);
    curl_close($ch);
    if(intval($aStatus["http_code"])==200){
        return $sContent;
    }else{
        return false;
    }
}

/**
 * post方式请求资源
 * @param string $url       基于的baseUrl
 * @param array $keysArr    请求的参数列表
 * @return string           返回的资源内容
 */
function http_post($url, $keysArr){
    $ch = curl_init();
    if(stripos($url,"https://")!==FALSE){
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }

    $aPOST = array();
    foreach($keysArr as $key=>$val){
        $aPOST[] = $key."=".urlencode($val);
    }
    $strPOST =  implode("&", $aPOST);

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($ch, CURLOPT_POST,true);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$strPOST);
    $sContent = curl_exec($ch);
    $aStatus = curl_getinfo($ch);
    curl_close($ch);
    if(intval($aStatus["http_code"])==200){
        return $sContent;
    }else{
        return false;
    }
}

function checkEmail($email,$uuid) {
    // 读取数据库
    $res = DB::table('employees')->where(['email'=>$email])->select('email','uuid')->first();
    if($res && $uuid !=$res['uuid']) E(L('_USER_EMAIL_EXIST_'), E_PLATFORM_SERVICE);
    return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

function checkMailbox($email){
    return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}


/**
 * 判断手机号格式
 */
function checkPhone($str){
	if(strlen($str) != 11) return false;
	if(!preg_match("/^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/", $str)) return false;
	return true;
}

/**
 * 给予文件id，返回文件读取链接
 * @param  array|string $ids 文件id
 * @return array|string|false 如多id，则返回array。否则直接返回string或false
 */
function getFileId($ids) {

    // 转换为数组
    if (is_string($ids)) {
       $ids = explode(',', $ids);
    }

    if (!is_array($ids))return false;



    // 读取数据库
    $res = DB::table('mi_files')->whereIn('id',$ids)->lists('file_path','id');
    //$res = M('files','mi_','API')->cache(true, 3600)->where(array('id' => array('in', $ids)))->getField('id,file_path');

    // 遍历返回

    foreach ($ids as $v) {
        $rs[$v] = array_key_exists($v, $res) ? getFilepath($res[$v]) : false;
    }

    // 如果是一个，则直接返回
    if (count($rs) == 1)
        return Config::get("defines.WEB_SITE_URL").reset($rs);

    return Config::get("defines.WEB_SITE_URL").$rs;
}

/**
 * 读取不同尺寸的缩略图
 * @param  string $img_url 原始文件路径
 * @param  string $type    获取缩略图类型
 * @return string|false    缩略图实体文件
 * @example （最后还应该用U方法读取）如：
 *          U('/file/read') . '?file=' . getThumbFile('Uploads/2015-12-14/12359647_224250202132_2.jpg');
 */
function getThumbFile($img_url, $type = 'middle') {
    // 静态数据
    static $thumbs = array();
    $thumbKey = md5(implode(':', func_get_args()));

    if (array_key_exists($thumbKey, $thumbs))
        return $thumbs[$thumbKey];

    // 图片静态数据
    static $imgInfos = array();
    $key = md5($img_url);

    // 获取当前读取的图片是否在配置中有
    $sizes = C('THUMB_SIZE_SPECS');
    if (!array_key_exists($type, $sizes)) {
        return $thumbs[$thumbKey] = false;
    }

    // 宽度，高度
    $size = $sizes[$type];
    if (!$size[0] || !$size[1]) {
        return $thumbs[$thumbKey] = false;
    }
    $width = $size[0]; // 宽度
    $height = $size[1]; // 高度
    // 获取文件相关数据
    if (array_key_exists($key, $imgInfos)) {
        $info = $imgInfos[$key];
    } else {
        $imgInfo = pathinfo($img_url);  // 获取文件信息
        $info = $imgInfos[$key] = array(
            'ext' => $imgInfo['extension'], // 文件后缀
            'path' => $imgInfo['dirname'], // 文件保存路径
            'name' => $imgInfo['filename'], // 原文件名
        );
    }

    // 缩略图文件名
    $fileTemp = C('THUMB_SAVE_NAME_TEMP');
    $filename = str_replace(
        array('{filename}', '{width}', '{height}', '{ext}'), array($info['name'], $width, $height, $info['ext']), $fileTemp
    );

    // 缩略图文件路径
    $filepath = $info['path']. '/' . $filename;

    return $filepath;
}

/**
 * 给予文件path返回图片读取链接
 */
function getFilepath($file) {
    return '/file/read?file=' . $file;
}

/**
 * 截取员工编号
 * @param unknown $employeeID
 * @return string
 */
function showEmployeeID($employeeID)
{
    $pos = strpos($employeeID,'-');
    return substr($employeeID,$pos+1);
}

/**
 * 图片post上传
 * @param unknown $url
 * @param unknown $data
 * @param number $timeout
 * @return string|unknown
 */
function curlPost($url, $data, $timeout=5){
    $ch = curl_init();
    $header = ["Accept-Charset: utf-8"];
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); //设置cURL允许执行的最长秒数
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $tmpInfo = curl_exec($ch);
    $errorno=curl_errno($ch);
    if ($errorno) {
        return json_encode(array('status'=>false,'msg'=>$errorno, 'code'=>400101));
    }else{
        return $tmpInfo;
    }
}

if (!function_exists('curlGet')){
    /**
     * get方式获取数据
     * @param  [type] $url [description]
     * @param  integer $timeout 超时时间
     * @return [type]      [description]
     */
    function curlGet($url, $timeout=5){
        $ch      = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result  = curl_exec($ch);
        $errorno = curl_errno($ch); //获取到错误信息
        curl_close($ch);

        if ($errorno)
            return json_encode(array('status'=>false,'msg'=>$errorno, 'code'=>400101));
        else
            return $result;
    }
}

/** Json数据格式化
 * @param  Mixed  $data   数据
 * @param  String $indent 缩进字符，默认4个空格
 * @return JSON
 */
function jsonFormat($data, $indent=null){

    // 对数组中每个元素递归进行urlencode操作，保护中文字符
    //要去掉影响转义 hexiong 2016-09-09
    //array_walk_recursive($data, 'jsonFormatProtect');

    // json encode
    $data = json_encode($data);

    // 将urlencode的内容进行urldecode
    $data = urldecode($data);

    // 缩进处理
    $ret = '';
    $pos = 0;
    $length = strlen($data);
    $indent = isset($indent)? $indent : '    ';
    $newline = "\n";
    $prevchar = '';
    $outofquotes = true;

    for($i=0; $i<=$length; $i++){

        $char = substr($data, $i, 1);

        if($char=='"' && $prevchar!='\\'){
            $outofquotes = !$outofquotes;
        }elseif(($char=='}' || $char==']') && $outofquotes){
            $ret .= $newline;
            $pos --;
            for($j=0; $j<$pos; $j++){
                $ret .= $indent;
            }
        }

        $ret .= $char;

        if(($char==',' || $char=='{' || $char=='[') && $outofquotes){
            $ret .= $newline;
            if($char=='{' || $char=='['){
                $pos ++;
            }

            for($j=0; $j<$pos; $j++){
                $ret .= $indent;
            }
        }

        $prevchar = $char;
    }

    return $ret;
}
function jsonFormatProtect(&$val){
    if($val!==true && $val!==false && $val!==null){
        $val = urlencode($val);
    }
}

//将一个对象数组转成格式化的json
function object_array($array) {
    if(is_object($array)) {
        $array = (array)$array;
    }
    if(is_array($array)) {
        foreach($array as $key=>$value) {
            $array[$key] = object_array($value);
        }
    }
    return $array;
}

//将一个对象数组转成真正的数组
function jsonDecode($array){
    return json_decode(json_encode($array), true);
}

//将数组对象的值全部转成string
function toString($var){
    return strval($var);
}

/**
 * 验证银行卡号格式
 */
function checkBankNumber($str){
    if(strlen($str) >=16 && strlen($str)<=19) return false;
    if(!preg_match("d{16}|\d{19})$/^(\var reg = /", $str)) return false;
    return true;
}

/**
 * 验证真实姓名的格式是否正确
 */
function checkRealName($realname) {
    if(!preg_match('/^([\xe4-\xe9][\x80-\xbf]{2}){2,4}$/', $realname)){//匹配2到四个汉字
        return false;
    }
    return true;
}

function getFirstCharter($str){
    if(empty($str)) return '';
    $fchar=ord($str{0});
    if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});
    $s1=iconv('UTF-8','gb2312',$str);
    $s2=iconv('gb2312','UTF-8',$s1);
    $s=$s2==$str?$s1:$str;
    $asc=ord($s{0})*256+ord($s{1})-65536;
    if($asc>=-20319&&$asc<=-20284) return 'A';
    if($asc>=-20283&&$asc<=-19776) return 'B';
    if($asc>=-19775&&$asc<=-19219) return 'C';
    if($asc>=-19218&&$asc<=-18711) return 'D';
    if($asc>=-18710&&$asc<=-18527) return 'E';
    if($asc>=-18526&&$asc<=-18240) return 'F';
    if($asc>=-18239&&$asc<=-17923) return 'G';
    if($asc>=-17922&&$asc<=-17418) return 'H';
    if($asc>=-17417&&$asc<=-16475) return 'J';
    if($asc>=-16474&&$asc<=-16213) return 'K';
    if($asc>=-16212&&$asc<=-15641) return 'L';
    if($asc>=-15640&&$asc<=-15166) return 'M';
    if($asc>=-15165&&$asc<=-14923) return 'N';
    if($asc>=-14922&&$asc<=-14915) return 'O';
    if($asc>=-14914&&$asc<=-14631) return 'P';
    if($asc>=-14630&&$asc<=-14150) return 'Q';
    if($asc>=-14149&&$asc<=-14091) return 'R';
    if($asc>=-14090&&$asc<=-13319) return 'S';
    if($asc>=-13318&&$asc<=-12839) return 'T';
    if($asc>=-12838&&$asc<=-12557) return 'W';
    if($asc>=-12556&&$asc<=-11848) return 'X';
    if($asc>=-11847&&$asc<=-11056) return 'Y';
    if($asc>=-11055&&$asc<=-10247) return 'Z';
    return null;
}

//删除所有空元素
function get_arr($arr)
{
    foreach ($arr as $k=>$v)
    {
       
        if(is_array($arr[$k]))
        {
            $arr[$k] = get_arr($arr[$k]);
        }
        else
        {
            if(empty($arr[$k]))
            {
                unset($arr[$k]);
            }
        }
    }
    return array_filter($arr);
}

function des_decrypt($encrypted, $salt)
{
    $encrypted = base64_decode($encrypted);
    $td = mcrypt_module_open('des', '', 'ecb', ''); // 使用MCRYPT_DES算法,cbc模式
    $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    $ks = mcrypt_enc_get_key_size($td);
    @mcrypt_generic_init($td, $salt, $iv);
    $decrypted = mdecrypt_generic($td, $encrypted);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);

    $pad = ord($decrypted{strlen($decrypted) - 1});
    if ($pad > strlen($decrypted))
        return false;
    if (strspn($decrypted, chr($pad), strlen($decrypted) - $pad) != $pad)
        return false;
    return substr($decrypted, 0, - 1 * $pad);
}

//删除二维数组重复的值
function a_array_unique($array)
{
    $out = array();
    foreach ($array as $key=>$value) {
        if (!in_array($value, $out))
        {
            $out[$key] = $value;
        }
    }
    return $out;
}

//松果商户号转uuid
function turn_uuid($str){
    $str    = preg_replace('/(.{8})(.*)/is','\1_\2',$str);
    $str    = preg_replace('/(.{13})(.*)/is','\1_\2',$str);
    $str    = preg_replace('/(.{18})(.*)/is','\1_\2',$str);
    $str    = preg_replace('/(.{23})(.*)/is','\1_\2',$str);   
    return $str;
}

//获取当前月的第一天
function getCurMonthFirstDay($date) {
    return date('Y-m-01', strtotime($date));
}

//获取当前月的最后一天
function getCurMonthLastDay($date) {
    return date('Y-m-d', strtotime(date('Y-m-01', strtotime($date)) . ' +1 month -1 day'));
}

//判断日期是否在某个月份
function determineDateIsTheMonth($date,$month){
    if($date >= getCurMonthFirstDay($month) && $date <= getCurMonthLastDay($month)){
        return true;
    }
    return false;
}

//获取时间差，返回迟到分钟
function timeDifference($time1,$time2){
   
    $time1 = explode(':', $time1);
    $time2 = explode(':', $time2);
    $data1 = $time1[0] - $time2[0];
    
    if($data1 > 0){
        $data2 =($time1[1]+$data1*60)  - $time2[1];
    }else{
        $data2 =$time1[1]  - $time2[1];
    }

   return $data2;
}

//获取时间差，返回早退分钟
function differenceTime($time1,$time2){
     
    $time1 = explode(':', $time1);
    $time2 = explode(':', $time2);
    $data1 = $time1[0] - $time2[0];

    $data2 =$time1[1]  - $time2[1];
   
    if($data1 > 0){
        $data2 =($time1[1]+$data1*60)  - $time2[1];
    }else{
        $data2 =$time1[1]  - $time2[1];
    }

   return $data2;
}

//获取日期之间相隔的天数
function differenceDay($date1,$date2){
    for($i = strtotime($date1); $i <= strtotime($date2); $i += 86400)
    {
        $ThisDate =date("Y-m-d",$i);
        $result[] = $ThisDate;
    }
    return $result;
}

function  strlenInfo ($data){
    $strlen = strlen($data);  //全部字符长度
    $tp = strpos($data,"-");  //limit之前的字符长度
    $result = substr($data,-$strlen,$tp);  //从头开始截取到指字符位置。
    return $result;
}

//判断时间格式是否是（10-09-16）格式，如果是则重新封装
function getTime($time){
    $list = explode('-', $time);
    if(strlen($list[0])<4){
        $year = '20'.$list[2];
        $month  = $list[0];
        $day = $list[1];
        $date =  $year.'-'.$month.'-'.$day;
    }
    return !empty($date) ? $date : $time;
}
//假如传过来的是天，则返回天时分
function getDayHours($date,$work_date,$type,$is_leave){
    if($date == 0){
        return '';
    }
    //如果不是请假类型
    if($is_leave == 0){
        switch ($type){
            //天换算成小时
            case 0:
                //判断如果传进来的是参数为整数
                if(!strpos($date,".")){
                    return $date.'天';
                }
                //如果是小数，并且时间大于1天
                if(strpos($date,".") && $date<1){
                    $hours = $date * $work_date;
                    $hours_int = intval($hours);
                    $hours_float = $hours- $hours_int;
                    $minute = intval($hours_float*60);
                    return  $hours_int.'小时'.$minute.'分钟';
                }
        
                if(strpos($date,".") && $date>1){
                    $day = intval($date);
                    $hours = $date - $day;
                    $hours =  $hours * $work_date;
                    $hours_int = intval($hours);
                    $hours_float = $hours- $hours_int;
                    $minute = intval($hours_float*60);
                    return  $day.'天'.$hours_int.'小时'.$minute.'分钟';
                }
                break;
            case 1:
                $hours_int = intval($date);
                $hours_float = $date- $hours_int;
                 
                //判断如果没有小数，并且小时数大于或等于，就直接返回天
                if(empty($hours_float) && $hours_int>=$work_date){
                    $day = $hours_int/$work_date;
                    if(is_int($day)){
                        return $day.'天';
                    }
                    $day_int = intval($day);
                    $hours = $day - $day_int;
                    $hours =  $hours * $work_date;
                    $hours_int = intval($hours);
                    $hours_float = $hours- $hours_int;
                    $minute = intval($hours_float*60);
                    if($minute > 0){
                        return  $day_int.'天'.$hours_int.'小时'.$minute.'分钟' ;
                    }
                    
                    return $day_int.'天'.$hours_int.'小时';                    
                }
                               
                if(empty($hours_float) && $hours_int<$work_date){
                    return $hours_int.'小时';
                }
                //将小数部分乘以工作日时长
                $hours_float = intval($hours_float * 60);
        
                //如果小于1小时，则返回分钟
                if($hours_float > 0 && $hours_int < $work_date){
                    return $hours_int.'小时'.$hours_float.'分钟';
                }
                //如果大于1小时，并且小时为整数，则直接返回小时
                if(!empty($hours_float) && $hours_int>=$work_date){
                    $result = $date/$work_date;
                    $day = intval($result);
                    $hours = $result - $day;
        
                    if(empty($hours)){
                        return $day.'天';
                    }
        
                    $hours = $hours * $work_date;
        
                    if($hours< 1){
                        $minute = intval($hours *60);
                        return $day.'天'.$minute.'分钟';
                    }
                    if($hours> 1 && is_int($hours)){
                        return $day.'天'.$hours.'小时';
                    }
                     
                    if($hours> 1){
                        $hours1 = intval($hours);
                        $minute = intval(($hours-$hours1)*60);
                        return $day.'天'.$hours1.'小时'.$minute.'分钟';
                    }
                }
                break;
        }
    }else{//否则就是请假类型，需要不满1小时算1小时
        switch ($type){
            //天换算成小时
            case 0:
                //判断如果传进来的是参数为整数
                if(!strpos($date,".")){
                    return $date.'天';
                }
                //如果是小数，并且时间大于1天
                if(strpos($date,".") && $date<1){
                    $hours = $date * $work_date;
                    $hours_int = intval($hours);
                    $hours_float = $hours- $hours_int;
                    $minute = intval($hours_float*60);
                    return  $hours_int.'小时'.$minute.'分钟';
                }
        
                if(strpos($date,".") && $date>1){
                    $day = intval($date);
                    $hours = $date - $day;
                    $hours =  $hours * $work_date;
                    $hours_int = intval($hours);
                    $hours_float = $hours- $hours_int;
                    $minute = intval($hours_float*60);
                    return  $day.'天'.$hours_int.'小时'.$minute.'分钟';
                }
                break;
            case 1:
                $hours_int = intval($date);
                $hours_float = $date- $hours_int;
                 
                //判断如果没有小数，并且小时数大于或等于，就直接返回天
                if(empty($hours_float) && $hours_int>=$work_date){
                    $day = $hours_int/$work_date;
                    return $day.'天';
                }
                if(empty($hours_float) && $hours_int<$work_date){
                    return $hours_int.'小时';
                }
                //将小数部分乘以工作日时长
                $hours_float = $hours_float * 60;
        
                //如果小于1小时，则返回分钟
                if($hours_float > 0 && $hours_int < $work_date){
                    $hours_int+=1;
                    return $hours_int++.'小时';
                }
                //如果大于1小时，并且小时为整数，则直接返回小时
                if(!empty($hours_float) && $hours_int>=$work_date){
                    $result = $date/$work_date;
                    $day = intval($result);
                    $hours = $result - $day;
        
                    if(empty($hours)){
                        return $day.'天';
                    }
        
                    $hours = $hours * $work_date;
        
                    if($hours< 1){
                        $minute = $hours *60;
                        if(!empty($minute)) $hours +=1;
                        return $day.'天'.$hours.'小时';
                    }
                    if($hours> 1 && is_int($hours)){
                        return $day.'天'.$hours.'小时';
                    }
                     
                    if($hours> 1){
                        $hours1 = intval($hours);
                        $minute = ($hours-$hours1)*60;
                        if(!empty($minute)) $hours1++;
                        return $day.'天'.$hours1.'小时';
                    }
                }
                break;
        }
    }   
}

//假如传过来的是天，则返回天时分(优化版)
function getDayHours1($date,$work_date,$is_leave){
    if(empty($date))  return '';
    switch ($is_leave){
        case 0:
            $hours_int = intval($date);
            $hours_float = $date- $hours_int;
             
            //判断如果没有小数，并且小时数大于或等于，就直接返回天
            if(empty($hours_float) && $hours_int>=$work_date){
                $day = $hours_int/$work_date;
                if(is_int($day)){
                    return $day.'天';
                }
                $day_int = intval($day);
                $hours = $day - $day_int;
                $hours =  $hours * $work_date;
                $hours_int = intval($hours);
                $hours_float = $hours- $hours_int;
                $minute = intval($hours_float*60);
                if($minute > 0){
                    return  $day_int.'天'.$hours_int.'小时'.$minute.'分钟' ;
                }
                
                return $day_int.'天'.$hours_int.'小时';                    
            }
                           
            if(empty($hours_float) && $hours_int<$work_date){
                return $hours_int.'小时';
            }
            //将小数部分乘以工作日时长
            $hours_float = intval($hours_float * 60);
    
            //如果小于1小时，则返回分钟
            if($hours_float > 0 && $hours_int < $work_date){
                return $hours_int.'小时'.$hours_float.'分钟';
            }
            //如果大于1小时，并且小时为整数，则直接返回小时
            if(!empty($hours_float) && $hours_int>=$work_date){
                $result = $date/$work_date;
                $day = intval($result);
                $hours = $result - $day;
    
                if(empty($hours)){
                    return $day.'天';
                }
    
                $hours = $hours * $work_date;
    
                if($hours< 1){
                    $minute = intval($hours *60);
                    return $day.'天'.$minute.'分钟';
                }
                if($hours> 1 && is_int($hours)){
                    return $day.'天'.$hours.'小时';
                }
                 
                if($hours> 1){
                    $hours1 = intval($hours);
                    $minute = intval(($hours-$hours1)*60);
                    return $day.'天'.$hours1.'小时'.$minute.'分钟';
                }
            }
            break;
        case 1:
            $hours_int = intval($date);
            $hours_float = $date- $hours_int;
             
            //判断如果没有小数，并且小时数大于或等于，就直接返回天
            if(empty($hours_float) && $hours_int>=$work_date){
                $day = $hours_int/$work_date;
                return $day.'天';
            }
            if(empty($hours_float) && $hours_int<$work_date){
                return $hours_int.'小时';
            }
            //将小数部分乘以工作日时长
            $hours_float = $hours_float * 60;
    
            //如果小于1小时，则返回分钟
            if($hours_float > 0 && $hours_int < $work_date){
                $hours_int+=1;
                return $hours_int++.'小时';
            }
            //如果大于1小时，并且小时为整数，则直接返回小时
            if(!empty($hours_float) && $hours_int>=$work_date){
                $result = $date/$work_date;
                $day = intval($result);
                $hours = $result - $day;
    
                if(empty($hours)){
                    return $day.'天';
                }
    
                $hours = $hours * $work_date;
    
                if($hours< 1){
                    $minute = $hours *60;
                    if(!empty($minute)) $hours +=1;
                    return $day.'天'.$hours.'小时';
                }
                if($hours> 1 && is_int($hours)){
                    return $day.'天'.$hours.'小时';
                }
                 
                if($hours> 1){
                    $hours1 = intval($hours);
                    $minute = ($hours-$hours1)*60;
                    if(!empty($minute)) $hours1++;
                    return $day.'天'.$hours1.'小时';
                }
            }
            break;
         }
}

//将三维数组转成二维
function conversionArray2($result){
    //循环遍历三维数组$arr3
    foreach($result as $value){      
        foreach($value as $key =>$val){
                $arr2[]=$val;
        }    
    }
    return !empty($arr2)?$arr2:[];
}

//计算个税
function calculateTax($money,$tax_money){
    if($money <=1500 ){
        $ratio = '0.03';
        $deduct = 0;
    }else if ($money > 1500 && $money <=4500) {
        $ratio = '0.1';
        $deduct = 105;
    }else if ($money > 4500 && $money <=9000) {
        $ratio = '0.2';
        $deduct = 555;
    } else if ($money > 9000 && $money <= 35000) {
        $ratio = '0.25';
        $deduct = 1005;
    } else if ($money > 35000 && $money <= 55000) {
        $ratio = '0.3';
        $deduct = 2755;
    } else if ($money > 55000 && $money <= 80000) {
        $ratio = '0.35';
        $deduct = 2755;
    } else{
        $ratio = '0.45';
        $deduct = 13505;
    }
    
    $taxInfo = decmialStr($money * $ratio - $deduct);
    
    return  [
        'money' => $taxInfo > 0 ? $taxInfo : 0,
        'ratio' =>$ratio, 
        'deduct' => $deduct,
        'point' => $tax_money,//税点
    ];   
}

//获取上个月
function getlastMonthDays($date){
    $timestamp=strtotime($date);
    $firstday=date('Y-m',strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)-1)));
    return array($firstday);
}


        

?>
